package myutil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.Map;

public class HttpUrlUtil {
    public static String handleHttpRequest(String url, Map<String,String> header,byte[] body){
        String result = "";
        BufferedReader in =null;
        try{
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
//            设置header
            for (String key : header.keySet()){
                httpURLConnection.setRequestProperty(key, header.get(key));
            }
            //设置请求body
            httpURLConnection.setDoOutput(true);

            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Content-Type","binary/octet-stream");
            OutputStream out=httpURLConnection.getOutputStream();
            out.write(body);
            out.flush();

            out.close();
            if (HttpURLConnection.HTTP_OK!=httpURLConnection.getResponseCode()){
                System.out.println("Http请求失败,状态码:"+ httpURLConnection.getResponseCode());
                return null;
            }
            in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String line;
            while ((line=in.readLine())!=null){
                result += line;
//                return result;
            }
            System.out.println(result);
            DecimalFormat    df   = new DecimalFormat("######0.00000");
            String result1 = df.format(result);
            return result1;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    // TODO: 2021/12/20

}
